<template>
  <div class="flex flex-column h-100">
    <div class="flex justify-between mb-10">
      <div>
        <!-- <export-dialog
          v-if="permission.export"
          export-func-name="alarmExportList"
          :file-name="$t('MENU_ALARM_HISTORY')"
          :page-data="pageData"
          :query-data="queryData"
        /> -->
        <el-button v-if="permission.export" icon="el-icon-download" type="primary" size="mini" @click="exportClick">{{
          $t('EXPORT')
        }}</el-button>
      </div>
      <div class="flex flex-wrap justify-end">
        <!-- 区域选择 -->
        <region-cascader
          style="width: 230px"
          class="mb-10"
          :multiple="true"
          :limit="2"
          @change="regionChange"
        />
        <el-select
          v-model="queryData.alarmType"
          clearable
          filterable
          style="width: 200px"
          class="ml-10 mb-10"
          size="mini"
          :placeholder="$t('ALARM_TYPE')"
        >
          <el-option
            v-for="(item, index) in alarmTypeList"
            :key="index"
            :value="item"
            :label="$t('ALARM_TYPE_' + item)"
          />
        </el-select>
        <el-select
          v-model="queryData.alarmLevel"
          clearable
          style="width: 150px"
          class="ml-10 mb-10"
          size="mini"
          :placeholder="$t('ALARM_LEVEL')"
        >
          <el-option
            v-for="item in dictList.ALARM_LEVEL"
            :key="item.id"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
        <el-select
          v-model="queryData.alarmStatus"
          clearable
          style="width: 150px"
          class="ml-10 mb-10"
          size="mini"
          :placeholder="$t('ALARM_STATUS')"
        >
          <el-option
            v-for="item in alarmStatusList"
            :key="item.id"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
        <!-- 录入时间 -->
        <el-date-picker
          v-model="queryData.dateTime"
          class="ml-10 mb-10"
          size="mini"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="-"
          :start-placeholder="$t('START_TIME')"
          :end-placeholder="$t('END_TIME')"
          align="right"
          style="width: 300px"
        />
        <el-input
          v-model.trim="queryData.keyword"
          class="ml-10 mb-10"
          style="width: 230px"
          maxlength="32"
          clearable
          size="mini"
          :placeholder="
            $t('DEVICE_CODE') +
              '/' +
              $t('DEVICE_NAME') +
              '/' +
              $t('CONFIRMER') +
              '/' +
              $t('CANCELER')
          "
          @keyup.enter.native="$debounce(search)"
        />
        <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{
          $t('QUERY')
        }}</el-button>
      </div>
    </div>
    <!--告警列表-->
    <TableView
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :operate-width="120"
      :cell-class="cellClassLevel"
      @operate="operate"
      @pageChange="pageChange"
    />

    <!-- 查看告警 -->
    <AlarmDetail
      :visible="alarmDetailVisible"
      :table-selected="tableSelected"
      view-type="history"
      @close="alarmDetailVisible = false"
    />

    <!-- 监控信息详情 -->
    <MonitorDetail
      v-if="monitorVisible"
      :dialog-visible.sync="monitorVisible"
      :params="tableSelected"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import AlarmRecordApi from '@/api/basebiz/AlarmRecordApi'
  import LogicSegmentApi from '@/api/oen/LogicSegmentApi'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  import { getParentsById, pickerOptionsClassMonth, handleAfsMaintText } from '@/utils/common.js'
  import { exportExcel } from '@/utils/jsonToExcel.js'
  import AlarmDetail from '../alarm/components/AlarmDetail'
  import ExportDialog from '@/components/ExportDialog'
  import RegionCascader from '@/components/RegionCascader'
  import MonitorDetail from '@/views/module/info/alarm/components/MonitorDetail'
  import TableView from '@/components/TableView'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    name: 'InfoHistoryPage',
    components: { AlarmDetail, ExportDialog, RegionCascader, TableView, MonitorDetail },
    data() {
      const _this = this
      return {
        queryData: {
          alarmLevel: '',
          keyword: '',
          alarmStatus: '',
          dateTime: '',
          alarmType: '',
          isAlarm: false
        },
        dialogVisible: false,
        tableData: [],
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        pickerOptions: pickerOptionsClassMonth,
        alarmDetailVisible: false,
        tableSelected: {},
        alarmStatus: '', // 修改告警状态
        currAlarm: null, // 当前选择告警
        monitorVisible: false,
        tableHeader: [
          {
            label: 'BELONGS_REGION_STATION_NAME',
            prop: 'regionTextNames',
            width: '160',
            fixed: 'left',
            configType: 'default'
          },
          {
            label: 'BELONGS_ROOM_NAME',
            prop: 'roomName',
            width: 200,
            configType: 'extend'
          },
          {
            label: 'ALARM_SOURCE_NAME',
            prop: 'deviceName',
            width: '160',
            fixed: 'left',
            configType: 'default',
            formatter(row) {
              return row.logicSegmentId ? _this.getSourceName(row.logicSegmentId) : row.deviceName
            }
          },
          {
            label: 'DEVICE_CODE',
            prop: 'deviceId',
            width: '160',
            configType: 'extend'
          },
          {
            label: 'ALARM_LEVEL',
            prop: 'alarmLevelText',
            width: '120'
          },
          {
            label: 'ALARM_STATUS',
            prop: 'alarmStatusText',
            width: '160',
            configType: 'default'
          },
          {
            label: 'ALARM_TYPE',
            prop: 'alarmTypeText',
            width: '160'
          },
          {
            label: 'ALARM_DESCRIPTION',
            prop: 'description',
            width: '250'
          },
          {
            label: 'START_TIME',
            prop: 'startTime',
            width: '160'
          },
          {
            label: 'END_TIME',
            prop: 'endTime',
            width: '160'
          },
          {
            label: 'CONFIRM_REASON',
            prop: 'confirmDesc',
            width: '160'
          },
          {
            label: 'CANCEL_REASON',
            prop: 'cancelDesc',
            width: '160'
          },
          {
            label: 'CONFIRM_TIME',
            prop: 'confirmTime',
            width: '160'
          },
          {
            label: 'CANCEL_TIME',
            prop: 'cancelTime',
            width: '160'
          },
          {
            label: 'CONFIRMER',
            prop: 'confirmer',
            width: '160'
          },
          {
            label: 'CANCELER',
            prop: 'canceler',
            width: '160'
          }
        ],
        alarmTypeList: [],
        logicSegmentData: []
      }
    },
    computed: {
      ...mapGetters(['dictList', 'getUser', 'getUserId', 'stationTree', 'dictMap', 'baseRegionList']),
      permission() {
        return this.$store.getters.getAuthData('info:history')
      },
      alarmStatusList() {
        // 告警状态
        return this.dictList.ALARM_STATUS.filter(
          item => item.value === 'CANCEL' || item.value === 'RESTORE'
        )
      }
    },
    activated() {
      this.loadData()
    },
    methods: {
      cellClassLevel({ row, column, rowIndex, columnIndex }) {
        if (column.property === 'alarmLevelText') {
          return `alarmLevelTextLabel lev${row.alarmLevel}`
        }
      },
      search() {
        this.pageData.page = 1
        searchData = {
          ...this.queryData
        }
        if (this.queryData.alarmLevel) searchData.alarmLevel = this.queryData.alarmLevel
        if (this.queryData.keyword) searchData.keyword = this.queryData.keyword.trim()
        if (this.queryData.regionIds) searchData.regionIds = this.queryData.regionIds
        if (this.queryData.alarmType) searchData.alarmType = this.queryData.alarmType
        if (this.queryData.alarmStatus) {
          searchData.alarmStatus = this.queryData.alarmStatus
        }
        if (this.queryData.dateTime) {
          searchData.startTime = this.queryData.dateTime[0]
          searchData.endTime = this.queryData.dateTime[1]
        }
        this.loadData()
      },
      getAlarmType() {
        AlarmRecordApi.recordAlarmTypes({ isActive: false }).then(res => {
          this.alarmTypeList = res || []
          if (this.queryData.alarmType && !res.includes(this.queryData.alarmType)) {
            this.queryData.alarmType = ''
          }
        })
      },
      async loadData() {
        this.getAlarmType()
        // 获取列表
        const data = {
          isAlarm: false,
          ...this.pageData,
          ...searchData
        }
        delete data.total
        const res = await AlarmRecordApi.alarmRecordPage(data)
        if (!res) return
        const { list, total } = res
        let logicSegmentIds = []
        logicSegmentIds = this.fmt_data(list)
        if (logicSegmentIds.length) {
          const result = await LogicSegmentApi.getListBySegmentIds(logicSegmentIds)
          this.logicSegmentData = result || []
        }
        this.tableData = list
        this.pageData.total = total
      },
      fmt_data(list) {
        const logicSegmentIds = []
        list.forEach(i => {
          if (i.regionId) {
            const trees = (getParentsById(this.stationTree, i.regionId, 'key') || []).reverse()
            if (trees.length > 0) {
              i.stationTextName = trees[trees.length - 1]['regionName'] // 站点名称
              i.regionTextNames = trees
                .map(i => i.regionName)
                .join('/') // 区域名称
              i.stationStatusText =
                this.dictMap['REGION_STATUS'][trees[trees.length - 1]['status']] // 站点状态
            } else {
              i.stationStatusText = ''
            }
          }
          i.roomName = this.getRoomName(i.roomId)
          i.logicSegmentId && logicSegmentIds.push(i.logicSegmentId)
          i.description = handleAfsMaintText(i.description) // 设备检修告警特殊处理
          i.trigger = this.$utils.handleServiceI18n(i.trigger)
          i.description = this.$utils.handleServiceI18n(i.description)
          i.deviceName = (i.device && i.device.deviceName) || ''
          i.alarmLevelText = this.dictMap['ALARM_LEVEL'][i['alarmLevel']] // 告警等级
          i.alarmTypeText = this.dictMap['ALARM_TYPE'][i['alarmType']] // 告警类型
          i.alarmStatusText = this.dictMap['ALARM_STATUS'][i['alarmStatus']] // 告警状态
          i.btns = this.getBtns(i)
        })
        return logicSegmentIds
      },
      // 机房
      getRoomName(roomId) {
        if (!roomId) return ''
        const stationData = this.baseRegionList.find(i => i.regionId === roomId)
        return stationData ? stationData.regionName : ''
      },
      getSourceName(logicSegmentId) {
        const data = this.logicSegmentData.find(i => i.segmentId === logicSegmentId)
        return data ? data.segmentName : ''
      },
      getBtns(row) {
        const btns = [
          {
            key: 'view',
            show: true,
            label: 'VIEW'
          },
          {
            key: 'monitor',
            show: row.alarmType === 'ILLEGAL_ENTRY' || row.alarmType === 'SOLAR_ENERGY_STOLEN',
            label: 'MONITOR'
          }
        ]
        return btns.filter(i => i.show)
      },
      operate(data) {
        switch (data.type) {
        case 'view':
          this.tableSelected = data.data
          this.alarmDetailVisible = true
          break
        case 'monitor':
          this.tableSelected = data.data
          this.monitorVisible = true
          break
        }
      },
      regionChange(data) {
        // 区域搜索条件改变
        // console.log(data)
        this.queryData.regionIds = data
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      },
      exportClick() {
        const data = {
          isAlarm: false,
          page: 1,
          size: 10000,
          ...searchData
        }
        this.$confirm(
          this.$t('ALARM_EXPORT_TIP') + '<br>' + this.$t('EXPORT_ALL_TIPS', { count: 10000 }),
          { type: 'warning', dangerouslyUseHTMLString: true }
        )
          .then(async() => {
            const res = await AlarmRecordApi.alarmRecordPage(data)
            if (!res) return
            const { list } = res
            let logicSegmentIds = []
            logicSegmentIds = this.fmt_data(list)
            if (logicSegmentIds.length) {
              const result = await LogicSegmentApi.getListBySegmentIds(logicSegmentIds)
              this.logicSegmentData = result || []
            }
            list.forEach(i => {
              i.deviceName = i.logicSegmentId ? this.getSourceName(i.logicSegmentId) : i.deviceName
            })
            this.exportExcel(list)
          })
          .catch(() => {})
      },
      exportExcel(data) {
        const hearder = [
          this.$t('BELONGS_REGION_STATION_NAME'),
          this.$t('ALARM_SOURCE_NAME'),
          this.$t('BELONGS_ROOM_NAME'),
          this.$t('DEVICE_CODE'),
          this.$t('ALARM_LEVEL'),
          this.$t('ALARM_STATUS'),
          this.$t('ALARM_TYPE'),
          this.$t('ALARM_DESCRIPTION'),
          this.$t('START_TIME'),
          this.$t('END_TIME'),
          this.$t('CONFIRM_REASON'),
          this.$t('CANCEL_REASON'),
          this.$t('CONFIRM_TIME'),
          this.$t('CANCEL_TIME'),
          this.$t('CANCELER')
        ]
        const jsonExcel = []
        const sheetNames = [this.$t('MENU_ALARM_HISTORY')]
        const relates = data.map((i, index) => {
          const item = [
            i.regionTextNames,
            i.deviceName,
            i.roomName,
            i.deviceId,
            i.alarmLevelText,
            i.alarmStatusText,
            i.alarmTypeText,
            i.description,
            i.startTime,
            i.endTime,
            i.confirmDesc,
            i.cancelDesc,
            i.confirmTime,
            i.cancelTime,
            i.confirmer,
            i.canceler
          ]
          return item
        })
        jsonExcel.push([hearder, ...relates])
        exportExcel(jsonExcel, this.$t('MENU_ALARM_HISTORY'), sheetNames, 'array')
        this.addLog()
      },
      addLog() {
        const obj = {
          api: '/',
          item: 'MENU_ALARM_HISTORY',
          object: '/',
          terminal: 'EXPORT',
          operateResult: true,
          realName: this.getUser.realName,
          content: JSON.stringify({
            currentUserId: this.getUserId,
            i18nKey: 'ALARM_EXPORT_ALL_LOG'
          })
        }
        OperateLogApi.addLog(obj)
      }
    }
  }
</script>

<style scoped></style>
